<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row.ivu-form-basic(ref="formData" :model="formData" :rules="rules" :label-width="90" v-if='hasFind')
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'select'")
              Select(v-if="item.fn" v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled" @on-change="listenCall(item.fn, item.model, $event)")
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
              Select(v-else v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable :disabled="item.isDisabled")
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.value"
                  :key="index"
                ) {{ c_item.label }}
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" clearable :disabled="item.isDisabled")
            template(v-if="item.type === 'radio'")
              RadioGroup.beautiful-radio-group(type="button" v-model="formData[item.model]")
                Radio.display-inline-block(v-for="(c_item, index) of item.radioArr" :label="c_item.value" :key="index") {{c_item.label}}
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval-date-140(:value="formData[item.model1]" :placeholder="item.placeholder1" type="date" @on-change="handleChangeDatePicker(item.model1, $event)")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval-date-140.mr-20(:value="formData[item.model2]" :placeholder="item.placeholder2" type="date" @on-change="handleChangeDatePicker(item.model2, $event)")
            template(v-if="item.type === 'button'")
              Button.search-btn(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              |合计
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
              Divider(type="vertical")
              |办理中
              span.text-info.pl-5.pr-5.font-weight {{tableComone.agentCount}}
              |条
              Divider(type="vertical")
              |已完结
              span.text-info.pl-5.pr-5.font-weight {{tableComone.doneCount}}
              |条
            .pull-right.table-title-btns
              //- Button.mr-10(type="info" @click="handleShowCreateCommercialWagesModal('create')" v-if='hasAdd') 新增
              Button(type="info" ghost @click="exportTreatmentEnjoyListSocialSecurity" v-if='hasExport') 导出
          template(slot-scope="{ row, index }" slot="action")
            //- Button.mr-10(type="text" size="small" @click="isDeleteModal(row, -99)" v-if='hasDelete') 删除
            Button.mr-10(type="text" size="small" @click="goEditNode(row)"  v-if='hasView') 查看
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )

    //- 新建弹窗
    CreateCommercialWagesModal(ref="CreateCommercialWagesModal" @query="searchFn")
</template>

<script>
import { Common } from '@/utils/common.js'
import { TreatmentApi } from '@/api/Treatment.api.js'
import { EnumApi } from '@/api/Enum.api.js'
import { SocialWagesThead } from './tableHead.js'
import _cloneDeep from 'clone-deep'
import { EmployeesApi } from '@/api/Employees.api.js'
import { TreatmentEnjoyManageApi } from '@/api/TreatmentEnjoyManage.api.js'
import CreateCommercialWagesModal from './modal/CreateCommercialWagesModal.vue'
import { TreatmentBasicsTypeApi } from '@/api/TreatmentBasicsType.api.js'
const colStyle = 'ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-12 ivu-col-span-xxl-8'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: 'commercialWagesManage', // 商保待遇管理

  components: {
    CreateCommercialWagesModal,
  },

  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },
    // 查询
    hasFind () {
      // return true
      return this.actionArr.indexOf('Find') > -1
    },
    // 查看
    hasView () {
      // return true
      return this.actionArr.indexOf('View') > -1
    },
    // 新增
    hasAdd () {
      // return true
      return this.actionArr.indexOf('Add') > -1
    },
    // 更新
    hasUpdate () {
      // return true
      return this.actionArr.indexOf('Update') > -1
    },
    // 删除
    hasDelete () {
      // return true
      return this.actionArr.indexOf('Delete') > -1
    },
    // 待遇环节基础数据批量导入
    hasImport () {
      // return true
      return this.actionArr.indexOf('Import') > -1
    },
    // 导出
    hasExport () {
      // return true
      return this.actionArr.indexOf('Export') > -1
    }
  },

  data () {
    return {
      thead: _cloneDeep(SocialWagesThead),
      tableData: [],
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        agentCount: 0, // 办理中
        doneCount: 0 // 办理中
      },
      formData: {
        enjoyType:3,
        employeeName: '',
        companyId: '',
        idCardNos: '',
        customerServiceId: '',
        treatmentTypeId: '',
        treatmentStatus: '',
        insuredTypeId: '',
        startTime: '',
        endTime: ''
      },
      formItem: [
        // { type: 'input', label: '客户名称：', placeholder: '请选择客户名称', prop: 'customerName', model: 'customerName', isDisabled: false, style: colStyle },
        // { type: 'select', label: '所属客服：', placeholder: '请选择所属客服', prop: 'customerServiceId', model: 'customerServiceId', isDisabled: false, style: colStyle, options: 'server' },
        { type: 'input', label: '姓名：', placeholder: '请输入姓名', prop: 'employeeName', model: 'employeeName', isDisabled: false, style: colStyle },
        { type: 'input', label: '身份证号码：', placeholder: '请输入身份证号码', prop: 'idCardNos', model: 'idCardNos', isDisabled: false, style: colStyle },
        // { type: 'select', label: '当前状态：', placeholder: '请选择当前状态', prop: 'treatmentStatus', model: 'treatmentStatus', isDisabled: false, style: colStyle, options: 'server' },
        // { type: 'select', label: '参保险种：', placeholder: '请选择待遇险种', prop: 'insuredTypeId', model: 'insuredTypeId', isDisabled: false, style: colStyle, options: 'insuredTypeId', fn: 'getInsuredTypeId' },
        // { type: 'select', label: '待遇名称：', placeholder: '请选择业务类型', prop: 'treatmentTypeId', model: 'treatmentTypeId', isDisabled: false, style: colStyle, options: 'treatmentTypeId' },
        { type: 'radio', label: '待遇状态：', placeholder: '请选择待遇状态', prop: 'treatmentStatus', model: 'treatmentStatus', isDisabled: false, style: colStyle, radioArr: [{ value: '', label: '全部' },{ value: '1', label: '办理中' }, { value: '2', label: '已完结' }, { value: '3', label: '已终止' }] },
        // { type: 'radio', label: '人员状态：', placeholder: '请选择人员状态', prop: 'treatmentStatus', model: 'treatmentStatus', isDisabled: false, style: colStyle, radioArr: [{ value: '1', label: '在职' }, { value: '0', label: '离职' }, { value: '-1', label: '离职未停保' }] },
        // { type: 'interval', label: '完结时间：', placeholder1: '开始日期', prop1: 'startTime', model1: 'startTime', placeholder2: '结束日期', prop2: 'endTime', model2: 'endTime', isDisabled: false, style: 'ivu-col-span-8' },
        { type: 'button', isDisabled: false }
      ],
      rules: {
      },
      selectedId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      arrListDown: {
        tempOps: [],
        defaultRadioArr: [{ value: '1', label: '是' }, { value: '0', label: '否' }],
        insuredTypeId: [],
        parameterstatus: [],
        server: [],
        treatmentTypeId: [],
        CustomerNameList: []
      },
      queryEmployeeList: []
    }
  },

  mounted () {
    this.servers()
    this.getInsuranceTypeList()
    this.getCustomerNameList()
    this.query()
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    // 数据字典
    getEnum () {
      let groupName = 'treatment.insuredTypeId,treatment.parameterstatus'
      Common.getEnum(groupName, this.arrListDown)
    },

    // 获取参保险种页面数据源
    async getInsuranceTypeList () {
      let res = await TreatmentBasicsTypeApi.getInsuranceTypeList()
      console.log('获取参保险种页面数据源: ', res)
      if (res.status === 200 && res.data.success) {
        var result = res.data.data
        var id = result[6].value
        this.formData.insuredTypeId = id
        var params = {
          insuredTypeId: id,
          HasPaging: true,
          PageIndex: 1,
          PageSize: 300
        }
        let ress = await TreatmentBasicsTypeApi.getBasicsTypeList(params)
        console.log('险种ress: ', ress)
        if (ress.status === 200 && ress.data.success && ress.data.data) {
          this.arrListDown.treatmentTypeId = ress.data.data.map(item => {
            return { label: item.text, value: item.value }
          })
        }
      }
    },


    // 获取客服
    async servers () {
      var params = {
        PageIndex: 1,
        PageSize: 100,
        Args: ''
      }
      Common.servers(params, this.arrListDown, 'server')
    },

    // 获取客户下拉内容
    async getCustomerNameList () {
      var params = {
        PageIndex: 1,
        PageSize: 10000
      }
      let res = await TreatmentEnjoyManageApi.customerNameList(params)
      console.log('res: ', res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.companyList = res.data.data.map(item => {
          return { label: item.value, value: item.key }
        })
      }
    },

    
    // 获取商保业务类型列表
    async getInsuredTypeId (modal, val) {
      if (val) {
        this.arrListDown.treatmentTypeId = []
        this.formData.treatmentTypeId = ''
        var params = {
          insuredTypeId: val,
          HasPaging: true,
          PageIndex: 1,
          PageSize: 300
        }
        let res = await TreatmentBasicsTypeApi.getList(params)
        console.log('客户薪资res: ', res)
        if (res.status === 200 && res.data.success && res.data.data) {
          this.formItem[5].isDisabled = false
          // this.formData.insuredTypeId = id
          this.arrListDown.treatmentTypeId = res.data.data.map(item => {
            return { label: item.treatmentName, value: item.id }
          })
        } else {
          this.formItem[5].isDisabled = true
        }
      }
    },

    // 搜索
    searchFn () {
      this.tableComone.pageIndex = 1
      this.query()
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query () {
      var params = {
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize,
        ...this.formData
      }
      params.insuredTypeId = params.insuredTypeId == '' ? '' : params.insuredTypeId
      let res = await TreatmentEnjoyManageApi.getList(params)
      console.log('分页查询接口res: ', res)
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data
        this.tableComone.totalRows = res.data.totalRows
        this.tableComone.agentCount = res.data.agentCount
        this.tableComone.doneCount = res.data.doneCount
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      this.selectedEmployeeArr = value.map((item) => {
        return { id: item.id, name: item.name }
      })
      this.selectedId = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedEmployeeArr)
      console.log('列表勾选数组2', this.selectedId)
    },

    // 日期选择
    handleChangeDatePicker (model, val) {
      console.log('model: ', model)
      console.log('val: ', val)
      this.formData[model] = val
    },

    // 导出待遇管理
    async exportTreatmentEnjoyListSocialSecurity () {      
      var params = {
        IdList: this.selectedId.join(','),
        HasPaging: true,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      }
      let res = await TreatmentEnjoyManageApi.export({ ...params, ...this.formData })
      console.log('导出待遇管理res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + '/' + res.data.data)
        window.open(baseUrl + '/' + res.data.data, '_blank')
      }
    },

    // 显示新增弹窗
    handleShowCreateCommercialWagesModal (actionType, id) {
      this.$refs.CreateCommercialWagesModal.queryEmployeeList = this.queryEmployeeList
      this.$refs.CreateCommercialWagesModal.arrListDown = {...this.$refs.CreateCommercialWagesModal.arrListDown, ...this.arrListDown}
      this.$refs.CreateCommercialWagesModal.isCreate = id ? false : true
      this.$refs.CreateCommercialWagesModal.getTreatmentParametersEnableList(this.formData.insuredTypeId)
      if (id) {
        this.$refs.CreateCommercialWagesModal.getModel(id)
      }
      this.$refs.CreateCommercialWagesModal.show(actionType, id)
    },

    // 显示完成弹窗
    handleShowCompleteModal (id) {
      this.$refs.CompleteSocialWagesModal.show(id)
    },

    // 删除||启用
    async handleDel (row) {
      var params = {
        Id: row.id,
      }
      let res = await TreatmentEnjoyManageApi.delete(params)
      console.log('删除||启用res: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
      } else {
        this.$Message.error(res.data.message)
      }
    },

    // 去往编辑环节
    goEditNode (row) {
      console.log(row,'去往编辑环节')
      this.$router.push({
        path: '/editCommercialNode',
        name: 'editCommercialNode',
        query: {
          id: row.id
        }
      })
    },

    // 是否删除前询问
    isDeleteModal (row) {
      this.$Modal.confirm({
        title: '是否确认删除该条信息',
        onOk: () => {
          this.handleDel(row)
        }
      })
    },
  } // methods end
}
</script>

<style lang="less" scoped>

</style>
